import axios from "axios"; // 引入axios
import qs from "qs";
import store from "@/store/store";
import router from "@/router";
import Vue from "vue";
const vm = new Vue();

//请求配置
// axios.defaults.timeout = 60000;
axios.defaults.timeout = 6000;
// axios.defaults.baseURL =  process.env.VUE_APP_BASE_API;
// axios.defaults.withCredentials = true;

//请求拦截
axios.interceptors.request.use(
  config => {
    // token
    // if (store.getters.token) {
    //   config.headers['token'] = getToken()
    // }
    if(!config['headers']['app-key']){
      config.headers['app-key'] = '5ab089ca77014874868482ebb85b424b';
    }
    if(localStorage.getItem('token')){
      config.headers['token'] = localStorage.getItem('token');
    }
    // config.headers['token'] = 'FB'
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

// 响应拦截
axios.interceptors.response.use(
  response => {
    // 如果返回success为true，说明接口请求成功，可以正常拿到数据，否则的话抛出错误
    if (response.data.success) {
      return Promise.resolve(response);
    } else {
      //统一处理接口报错
      // 限制弹出框多次弹出
      if (document.getElementsByClassName('vs-notifications').length === 0 && response.data.code !== 102) {
        vm.$vs.notify({
          text: response.data.message,
          color: "danger",
          icon: "error"
        });
      }

      return Promise.reject(response);
    }
  },
  //错误状态码
  error => {
    if (error.response && error.response.data.errorCode) {
      switch (error.response.data.errorCode) {
        case 5000:
          this.$vs.notify({
            text: `${error.response.data.message}`
          });
          break;
        // 403 token过期
        case 403:
          // 清除token
          localStorage.removeItem("token");
          // 跳转登录页面，并将要浏览的页面fullPath传过去，登录成功后跳转需要访问的页面
          setTimeout(() => {
            router.replace({
              path: "/pages/login",
              query: {
                redirect: router.currentRoute.fullPath
              }
            });
          }, 1000);
          break;

        case 404:
          break;
        // 其他错误，直接抛出错误提示
        default:
      }
      return Promise.reject(error.response);
    } else {
      if (document.getElementsByClassName('vs-notifications').length === 0) {
        vm.$vs.notify({
          text: "网络连接失败",
          color: "danger",
          icon: "error"
        });
      }
      return Promise.reject(error);
    }
  }
);

/**
 * 封装get请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 * @returns {Promise}
 */
// export function get(url, params = {}) {
//   return new Promise((resolve, reject) => {
//     axios
//       .get(url, params)
//       .then(res => {
//         resolve(res);
//       })
//       .catch(err => {
//         reject(err.data);
//       });
//   });
// }

// /**
//  * 封装post请求
//  * @param {String} url [请求的url地址]
//  * @param {Object} params [请求时携带的参数]
//  * @returns {Promise}
//  */
// export function post(url, params = {}) {
//   return new Promise((resolve, reject) => {
//     axios
//       .post(url, qs.stringify(params))
//       .then(res => {
//         resolve(res.data);
//       })
//       .catch(err => {
//         reject(err.data);
//       });
//   });
// }

/**
 * 封装put请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function put(url, data = {}) {
  return new Promise((resolve, reject) => {
    axios.put(url, data).then(
      response => {
        resolve(response.data);
      },
      err => {
        reject(err);
      }
    );
  });
}

export default axios;
